/*
 * ResourceManager.cpp
 *
 *  Created on: Mar 24, 2010
 *      Author: dcrown
 */

#include <windows.h>
#include <fstream>
#include "ResourceManager.h"
#include <vector>
#include <string>

const char MP_DELIM = ',';
const int MP_LINE_LENGTH = 3;

void ResourceManager::Create()
{

}

MovePattern* ResourceManager::ReadMovePattern(const char* filename)
{
	bool success = false;

	ifstream mpFile(filename, ios::in);

	if (mpFile.is_open())
	{
		vector<int> times;
		vector<unsigned short> bearings;
		vector<float> speeds;
		vector<string> tokens;
		vector<string>::iterator iter;

		string line;
		string temp;
		int index = 0;

		while (!mpFile.eof())
		{
			getline(mpFile, line);
			tokens = SplitString(line, MP_DELIM);

			if (tokens.size() == MP_LINE_LENGTH)
			{
				if (ContainsOnlyDigits(tokens))
				{
					times.push_back(atoi(tokens[0]));
					bearings.push_back(atoi(tokens[1]));
					speeds.push_back(atof(tokens[2]));
				}
				else
				{
					Logger::getInstance().LOG(Logger::FATAL, "Non-digit characters found in MovePattern: %s, \"%s\"", filename, line.c_str());
					return NULL;
				}
			}
			else
			{
				Logger::getInstance().LOG(Logger::FATAL, "Incorrect # of tokens found in MovePattern: %s, \"%s\"", filename, line.c_str());
				return NULL;
			}
		}
		mpFile.close();

		MovePattern* mp = new MovePattern;
		mp->Create(times, bearings, speeds, false, 450, 15, 0);
	}
	else
	{
		Logger::getInstance().LOG(Logger::FATAL, "Couldn't open MovePattern: %s", filename);
		return NULL;
	}
}

vector<string> ResourceManager::SplitString(string line, char delim)
{
	vector<string> tokens;
	string token;

	int start = 0;
	int stop = line.find(delim, start);

	while (stop != string::npos);
	{
		string token = line.substr(start, stop-start);
		Logger::getInstance().LOG(Logger::DEBUG, "Adding: %s", token.c_str());
		tokens.add(token);

		start = stop+1;
		stop = line.find(delim, start);
	}

	return tokens;
}

bool ResourceManager::ContainsOnlyDigits(vector<string> theStrings)
{
	vector<string>::iterator iter;

	iter = theStrings.begin();
	while (iter != theStrings.end())
	{
		int length = iter->length;
		for (int i = 0; i < length; i++)
		{
			if (((*iter)[i] > '9') || ((*iter)[i] < '0'))
			{
				return false;
			}
		}
	}

	return true;
}
